﻿/// <reference path="select2/js/select2.full.js" />
/// <reference path="jquery-3.4.1.min.js" />
/// <reference path="sha1.min.js" />
/// <reference path="ArrayHelper.js" />

var globalSettings = {
    ajaxShadow: null,
    ajaxCount: 0
};

var ajaxShadowBlockHtml = '<div class="shadow-ajax"><img src="/img/loading2.gif" style="position:fixed; display:block; margin-left:-16px; margin-top:-16px; top:50%;left:50%; width:32px; height:32px; " /></div>'

top.window['__ajax__count'] = 0;
var topAjaxCount = top.window['__ajax__count'];

//处理ajax效果
function handAjaxShadow(IsShadowShow) {
    if (IsShadowShow) {
        topAjaxCount++;
        if (!top.$('.shadow-ajax').is(':visible')) {
            top.$('.shadow-ajax').show();
        }
    }
    else {
        topAjaxCount--;
        if (topAjaxCount == 0) {
            top.$('.shadow-ajax').hide();
        }
        else {
            if (!top.$('.shadow-ajax').is(':visible')) {
                top.$('.shadow-ajax').show();
            }
        }
    }
}

$(function () {
    if ($('.shadow-ajax').length == 0) {
        $('body').append(ajaxShadowBlockHtml);
    }
});

$.fn.extend({

    //绑定数据到Table方法
    bindTable: function (bindData, fnCallback) {
        var _tables = $(this);
        _tables.each(function () {

            if (!$.isArray(bindData)) {
                throw '自定义方法[bindTable]Info:绑定的数据不是数组';
                return false;
            }

            var _tableHead = $(this).children('thead');
            var _tableBoty = $(this).children('tbody');

            if (bindData.length == 0) {
                var emptyHtml = '<td class="text-center bg-light" colspan="' + _tableHead.find('th:visible').length + '">暂无数据</td>';
                _tableBoty.html(emptyHtml);
                return false;
            }

            var _tableCols = [];
            _tableHead.find('th').each(function () {
                var currTH = $(this);
                var tempCol = { colname: currTH.getAttr('data-col'), colclass: currTH.getAttr('data-class') };
                _tableCols.push(tempCol);
            });

            var finallHtml = '';
            for (var i = 0; i < bindData.length; i++) {
                var ro = bindData[i];
                finallHtml += '<tr>';
                for (var j = 0; j < _tableCols.length; j++) {
                    var col = _tableCols[j];
                    if (col.colname == 'chk') {
                        var dataValue = '<input type="checkbox" />';
                        finallHtml += '<td class="' + col.colclass + '">' + dataValue + '</td>';
                    }
                        //else if (col.colname == 'rownum') {
                        //    var dataValue = (i+1);
                        //    finallHtml += '<td class="' + col.colclass + '">' + dataValue + '</td>';
                        //}
                    else {
                        var dataValue = col.colname != '' ? ro[col.colname] : '';
                        finallHtml += '<td class="' + col.colclass + '" >' + dataValue + '</td>';
                    }

                }
                finallHtml += '</tr>';
            }

            _tableBoty.html(finallHtml);
            _tableBoty.find('tr').click(function () {
                var firstCheckbox = $(this).find('input[type=checkbox]:first');
                if (firstCheckbox.is(':checked')) {
                    firstCheckbox.prop('checked', false);
                    $(this).removeClass('selected');
                }
                else {

                    firstCheckbox.prop('checked', true);
                    $(this).addClass('selected');
                }
            });
        });

        if ($.isFunction(fnCallback)) {
            fnCallback();
        }
    },

    //从Table中获得唯一选择的行的指定data-col属性对应列的信息
    getTableOnlyOneChecked: function (colDataProperty) {
        var _self = $(this);

        var colIndex = _self.find('th[data-col="' + colDataProperty + '"]').index();
        var checkedSize = _self.find('input[type=checkbox]:checked').length;

        if (checkedSize == 0) {
            sysAlert.error("请先勾选一条信息进行操作");
            return null;
        }
        else if (checkedSize > 1) {
            sysAlert.error("该操作每次只能针对一条信息");
            return null;
        }
        else {
            editId = _self.find('input[type=checkbox]:checked').parents('tr').find('td').eq(colIndex).text();
            return editId;
        }
    },

    //从Table中获得所有勾选的行的指定data-col属性对应列的信息
    getTableAllChecked: function (colDataProperty) {
        var _self = $(this);

        var colIndex = _self.find('th[data-col="' + colDataProperty + '"]').index();
        var checkedSize = _self.find('input[type=checkbox]:checked').length;

        if (checkedSize == 0) {
            sysAlert.error("请先勾选一条信息进行操作");
            return null;
        }
        else {
            var editIdArr = [];
            _self.find('input[type=checkbox]:checked').each(function () {
                var that = $(this);
                var singleId = that.parents('tr').find('td').eq(colIndex).text();
                editIdArr.push(singleId);
            });
            return editIdArr;
        }
    },

    //获取自定义属性方法
    getAttr: function (attributeName) {
        var directValue = $(this).attr(attributeName);
        if (directValue == undefined || directValue == null) {
            return '';
        }
        else {
            return directValue;
        }
    },

    //清理表单数据方法
    clearData: function () {
        $(this).find('[data-col]').val('').text('');
    },

    //绑定表单数据方法
    bindData: function (dataObj, fnCallback) {
        for (var pInfo in dataObj) {
            var targetItem = $(this).find('[data-col="' + pInfo + '"]');
            if (targetItem.length == 1) {
                if (targetItem.is('span') || targetItem.is('p') || targetItem.is('label')) {
                    targetItem.text(dataObj[pInfo])
                }
                else if (targetItem.is('div')) {
                    targetItem.html(dataObj[pInfo]);
                }
                else if (targetItem.is('input[type=checkbox]')) {
                    var targetValue = dataObj[pInfo];
                    if (targetValue == 1) {
                        targetItem.prop('checked', true);
                    }
                    else {
                        targetItem.prop('checked', false);
                    }
                }
                else {
                    targetItem.val(dataObj[pInfo]);
                }
            }
            else if (targetItem.length > 1 && targetItem.eq(0).is('input[type=radio]')) {

                var targetValue = dataObj[pInfo];

                targetItem.each(function () {
                    $(this).prop('checked', false);
                });

                targetItem.each(function () {
                    if ($(this).attr('value') == targetValue || $(this).prop('value') == targetValue) {
                        $(this).prop('checked', true);
                        return false;
                    }
                });
            }
        }

        if ($.isFunction(fnCallback)) {
            fnCallback(dataObj);
        }
    },

    //获得表单数据方法
    getData: function (reqFunc) {
        var dataObj = {};
        if (!$.isNullOrUndefinedOrEmpty(reqFunc)) {
            dataObj.rtype = reqFunc;
        }

        var _self = $(this);
        _self.find('[data-col]').each(function () {
            var pName = $(this).attr('data-col');
            if ($(this).is('span') || $(this).is('p') || $(this).is('label') || $(this).is('div')) {
                dataObj[pName] = $(this).text();
            }
            else if ($(this).is('input[type=checkbox]')) {
                if ($(this).is(':checked')) {
                    dataObj[pName] = 1;
                }
                else {
                    dataObj[pName] = 0;
                }
            }
            else if ($(this).is('input[type=radio]')) {
                if ($.isNullOrUndefinedOrEmpty(dataObj[pName])) {
                    var radioName = $(this).prop('name');
                    if (!$.isNullOrUndefinedOrEmpty(radioName)) {
                        var controlValue = $('input[name="' + radioName + '"]:checked').val();
                        dataObj[pName] = controlValue;
                    }
                }
            }
            else {
                dataObj[pName] = $(this).val();
            }

            if ($(this).attr('data-secret') == '1') {
                dataObj[pName] = sha1(dataObj[pName]);
            }

            //验证
            if ($(this).attr('data-required') == '1' && $.isNullOrUndefinedOrEmpty(dataObj[pName])) {
                var chineseName = $(this).attr('data-chs');
                top.sysAlert.Error(chineseName + '不能为空');
                dataObj = null;
            }
        });

        return dataObj;
    },

    //绑定某个分类的系统代码列表到单个下拉列表
    bindSysCodeDropdownList: function (flag, fnCallback) {

        var _self = $(this);

        $.rajax('/admin/handler/common.ashx', { rtype: 'GetCodeList', 'flag': flag }, function (retobj) {
            if (retobj.flag == 1) {
                var bindData = retobj.data;
                var optionsHtml = '<option value="">全部</option>';
                for (var i = 0; i < bindData.length; i++) {
                    var ro = bindData[i];
                    optionsHtml += '<option value="' + ro.Code + '">' + ro.Meaning + '</option>';
                }

                _self.html(optionsHtml);
            }
            else {
                top.fyAlert.msg(retobj.msg, { icon: 3, animateType: 3 });
            }

            if ($.isFunction(fnCallback)) {
                fnCallback();
            }
        });
    },

    //绑定多个分类的系统代码列表到对应下拉列表
    bindMutliCodeDropdownList: function (flagArr, fnCallback, emptyText) {

        var _self = $(this);

        if (!$.isArray(flagArr)) {
            throw 'bindMutliCodeDropdownList方法传入参数[flagArr]必须是数组';
            return false;
        }

        $.rajax('/admin/handler/common.ashx', { rtype: 'GetCodeListByFlagList', 'flagArr': flagArr }, function (retobj) {
            var codeListArr = retobj.data;

            var finallEmptyText = '';
            if ($.isNullOrUndefinedOrEmpty()) {
                finallEmptyText = '全部';
            }
            else {
                finallEmptyText = emptyText;
            }

            for (var i = 0; i < flagArr.length; i++) {
                var oneFlag = flagArr[i];
                var tempCodeList = codeListArr[i];

                if (tempCodeList.length > 0) {
                    var theSelect = _self.find('[data-flag="' + oneFlag + '"]');
                    var optionsHtml = (finallEmptyText == '_none') ? '' : '<option value="">' + finallEmptyText + '</option>';

                    for (var j = 0; j < tempCodeList.length; j++) {
                        var ro = tempCodeList[j];
                        optionsHtml += '<option value="' + ro.Code + '">' + ro.Meaning + '</option>';
                    }
                    theSelect.html(optionsHtml)
                }
            }

            if ($.isFunction(fnCallback)) {
                fnCallback();
            }
        });
    },

    //绑定某个分类的系统代码列表到单个带搜索框的下拉列表
    bindSysCodeSelect2: function (flag, options, fnCallback) {

        var _self = $(this);
        _self.html('');

        var defaultOptions = {
            emptyText: '==请选择==',
        };

        var finallOptions = $.isNullOrUndefinedOrEmpty(options) ? defaultOptions : $.extend(defaultOptions, options);

        $.rajax('/admin/handler/common.ashx', { rtype: 'GetCodeList', 'flag': flag }, function (retobj) {
            if (retobj.flag == 1) {
                var bindData = retobj.data;
                var optionsHtml = '<option value="">'+ finallOptions.emptyText +'</option>';
                for (var i = 0; i < bindData.length; i++) {
                    var ro = bindData[i];
                    optionsHtml += '<option value="' + ro.Code + '">' + ro.Meaning + '</option>';
                }

                _self.html(optionsHtml);
                _self.select2();
            }
            else {
                top.fyAlert.msg(retobj.msg, { icon: 3, animateType: 3 });
            }

            if ($.isFunction(fnCallback)) {
                fnCallback();
            }
        });
    },

    //绑定多个分类的系统代码列表到对应带搜索框的下拉列表
    bindMutliCodeSelect2: function (flagArr, fnCallback, emptyText) {

        var _self = $(this);

        if (!$.isArray(flagArr)) {
            throw 'bindMutliCodeDropdownList方法传入参数[flagArr]必须是数组';
            return false;
        }

        $.rajax('/admin/handler/common.ashx', { rtype: 'GetCodeListByFlagList', 'flagArr': flagArr }, function (retobj) {
            var codeListArr = retobj.data;

            var finallEmptyText = '';
            if ($.isNullOrUndefinedOrEmpty()) {
                finallEmptyText = '全部';
            }
            else {
                finallEmptyText = emptyText;
            }

            for (var i = 0; i < flagArr.length; i++) {
                var oneFlag = flagArr[i];
                var tempCodeList = codeListArr[i];

                if (tempCodeList.length > 0) {
                    var theSelect = _self.find('[data-flag="' + oneFlag + '"]');
                    theSelect.html('');
                    var optionsHtml = (finallEmptyText == '_none') ? '' : '<option value="">' + finallEmptyText + '</option>';

                    for (var j = 0; j < tempCodeList.length; j++) {
                        var ro = tempCodeList[j];
                        optionsHtml += '<option value="' + ro.Code + '">' + ro.Meaning + '</option>';
                    }
                    theSelect.html(optionsHtml);
                    theSelect.select2();
                }
            }

            if ($.isFunction(fnCallback)) {
                fnCallback();
            }
        });
    },

    //绑定数组数据到单个带搜索框的下拉列表
    bindSelect2Data: function (dataArr, options, fnCallback) {
        var _self = $(this);

        if (!$.isArray(dataArr)) {
            throw '[bindSelect2Data]方法报错：要绑定的数据不是数组';
        }

        var defaultOptions = {
            emptyText: '==请选择==',
            textCol: 'text',
            valueCol: 'id',
        };

        var finallOptions = $.isNullOrUndefinedOrEmpty(options) ? defaultOptions : $.extend(defaultOptions, options);

        _self.each(function () {
            var _this = $(this);
            var finallHtml = '<option value="">' + finallOptions.emptyText + '</option>'
            for (var i = 0; i < dataArr.length; i++) {
                var item = dataArr[i];
                finallHtml += '<option value="' + item[finallOptions.valueCol] + '">' + item[finallOptions.textCol] + '</option>';
            }

            _this.html(finallHtml);
            _this.select2();
        });

        if ($.isFunction(fnCallback)) {
            fnCallback();
        }
    },

    //绑定页码
    setPager: function (pageInfo, getDataFn) {
        var _self = $(this);

        _self.pagination({
            pageCount: pageInfo.PageCount,
            current: pageInfo.PageIndex,
            jump: false,
            coping: true,
            keepShowPN: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '上一页',
            nextContent: '下一页',
            jumpBtn: '跳转',
            mode: 'unfixed',
            count: 5,
            activeCls: 'current',
            jumpBtnCls: 'current',
            callback: function (api) {
                console.log(api.getCurrent());//current为当前页-1,如当前是第一页current为0
                var current = api.getCurrent();
                getDataFn(current, pageInfo.PageSize);
            }
        }, function () {
            var pageSplitHtml = '当前是第' + pageInfo.PageIndex + '页，共' + pageInfo.PageCount + '页'
                + '，共' + pageInfo.RecordCount + '条，每页显示<select class="selPageSize"><option value="10">10</option><option value="15">15</option><option value="20">20</option><option value="50">50</option></option> </select>条';
            _self.append(pageSplitHtml);

            _self.find('.selPageSize').val(pageInfo.PageSize).change(function () {
                var pageSizeNew = $(this).val();
                getDataFn(1, pageSizeNew);
            });
        });
    },
});

//ajax同步逻辑
function syncAjaxState(IsStart) {
    if (IsStart) {
        globalSettings.ajaxCount++;
    }
    else {
        globalSettings.ajaxCount--;
    }
    if (globalSettings.ajaxCount == 0) {
        globalSettings.ajaxShadow.destory();
        globalSettings.ajaxShadow = null;
    }
    else {
        showLoading();
    }
}

/*
 * 获取地址栏地址
 */
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

$.extend({
    rajax: function (reqUrl, reqData, fnSuccess, fnFailed) {

        for (var item in reqData) {
            if (typeof reqData[item] !== 'string') {
                reqData[item] = JSON.stringify(reqData[item]);
            }
        }

        $.ajax({
            url: reqUrl,
            data: reqData,
            cache: false,
            type: 'POST',
            beforeSend: function () {
                handAjaxShadow(true);
            },
            success: function (msg) {
                if (msg != null && typeof msg === 'string') {
                    msg = $.parseJSON(msg);
                }
                if (msg.flag == 1) {
                    if ($.isFunction(fnSuccess)) {
                        fnSuccess(msg);
                    }
                    else {
                        top.sysAlert.success(msg.msg);
                    }
                }
                else {
                    if ($.isFunction(fnFailed)) {
                        fnFailed(msg);
                    }
                    else {
                        top.sysAlert.Error(msg.msg);
                    }
                }

                handAjaxShadow(false);
            },
            error: function (e1, e2, e3) {
                console.log('异步请求异常：');
                console.log('异常对象1：');
                console.log(e1);
                console.log('异常对象2：');
                console.log(e2);
                console.log('异常对象3：');
                console.log(e3);
                handAjaxShadow(false);
            }
        });
    },

    isNullOrUndefinedOrEmpty: function (_value) {
        if (_value == undefined || _value == null || _value == '') {
            return true;
        }
        else {
            return false;
        }
    },


});

//开启遮罩层方法
function showLoading() {
    globalSettings.ajaxShadow = top.fyAlert.msg("加载中...", { icon: 5, animateType: 4, shadow: [0.3, '#000'] });
}

//初始化页面上的kindeditor
function InitKindEditors(selector, KValue, fnCallback) {
    var K = KValue;
    var ncount = $(selector).find('[data-isreach="1"]').length;
    var creatCount = 0;
    $(selector).find('[data-isreach="1"]').each(function () {
        var selectorExp = $(this).attr('data-col');
        var editorObj = K.create('textarea[data-col="' + selectorExp + '"]', {
            cssPath: '/js/kindeditor/plugins/code/prettify.css',
            uploadJson: '/Handler/Intensification/Upload.ashx',
            fileManagerJson: '/Handler/Intensification/FileManager.ashx',
            allowFileManager: true,
            afterCreate: function () {

                creatCount++;
                if (ncount == creatCount) {
                    if ($.isFunction(fnCallback)) {
                        fnCallback();
                    }
                }
            }
        });
        $(this).data('editor', editorObj);
    });

    prettyPrint();
}

/*
 * 加载时间控件的方法
*/
function InitDateInput(jqContainer) {
    $('.input-date').datetimepicker({
        format: 'yyyy-mm-dd'
        , minView: 'month'
        , autoclose: true
        , language: 'zh-CN'
        , clearBtn: true
    });
    $('.input-date-time').datetimepicker({
        format: 'yyyy-mm-dd hh:ii:00'
        , minView: 'hour'
        , autoclose: true
        , language: 'zh-CN'
        , clearBtn: true
        , container: jqContainer
    });
}

//js生成guid方法
function newGuid() {
    var guid = "";
    for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
            guid += "-";
    }

    return guid;
}

/*
 * 系统弹窗封装
*/
window.sysAlert = {
    success: function (msg) {
        $.message({
            message: msg,
            type: 'success',
            duration: 2500,
            showClose: true,
        });
    },
    error: function (msg) {
        $.message({
            message: msg,
            type: 'error',
            duration: 2500,
            showClose: true,
        });
    },
    warn: function (msg) {
        $.message({
            message: msg,
            type: 'warning',
            duration: 2500,
            showClose: true,
        });
    },
    info: function (msg) {
        $.message({
            message: msg,
            type: 'info',
            duration: 2500,
            showClose: true,
        });
    },
    Error: function (msg) {
        Dialog.error("系统提示", msg);
    },

    ShowIframe: function (iframeSrc, dialogTitle, dialogWidth, dialogHeight) {

        if ($.isNullOrUndefinedOrEmpty(dialogWidth) || !$.isNumeric(dialogWidth)) {
            dialogWidth = 800;
        }
        if ($.isNullOrUndefinedOrEmpty(dialogHeight) || !$.isNumeric(dialogHeight)) {
            dialogHeight = 600;
        }

        Dialog({
            title: dialogTitle,
            width: dialogWidth,
            iframeContent: {
                src: iframeSrc,
                height: dialogHeight
            },
            showButton: false
        });

    },

    CloseDialog: function () {
        parent.Dialog.close();
    },

    Confirm: function (msg, fnCallback, dialogTitle) {

        if ($.isNullOrUndefinedOrEmpty(dialogTitle)) {
            dialogTitle = '系统提示';
        }

        Dialog({
            title: dialogTitle,
            content: msg,
            ok: {
                callback: function () {
                    fnCallback();
                }
            }
        });
    }
}



//绑定带有联动效果的下拉框（未完成，不需要了，有更好的实现方式了）
//bindCasCadeSelect2: function (dataArr, options, fnCallback) {

//    var _selects = $(this);

//    if (_selects.length <= 1) {
//        throw '[bindCasCadeSelect2]方法报错：要绑定级联下拉框至少需要2个对象';
//    }

//    if (!$.isArray(dataArr)) {
//        throw '[bindCasCadeSelect2]方法报错：要绑定的数据不是数组';
//    }

//    var defaultOptions = {
//        emptyText: '==请选择==',
//        textCol: 'text',
//        valueCol: 'id',
//        parentValueCol: 'pid',
//    };

//    var finallOptions = $.isNullOrUndefinedOrEmpty(options) ? defaultOptions : $.extend(defaultOptions, options);

//    _selects.each(function () {
//        var _select = $(this);

//        if ($.isNullOrUndefinedOrEmpty(_select.attr('data-cascade-parentid'))) {
//            throw '[bindCasCadeSelect2]方法报错：要绑定的下拉框属性没有正确设置';
//        }

//        var tempId = _select.attr('data-cascade-parentid');

//        if (dataArr.getItemByValue(finallOptions.parentValueCol, tempId) == null) {
//            throw '[bindCasCadeSelect2]方法报错：父id【' + tempId + '】没有找到下级数据';
//        }
//    });


//},
